#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>

#define SIZE_COMMAND 256
#define SIZE_NAME 128
#define SIZE_COMMAND_PARSE 10
void begin();
void output_error();
int input_command(char*);
void parse_command(char*,char*,char**);
void use_command(char*,char**);
int main(){
	begin();
	return 0;
}
void begin(){
	while(1){
		char command[SIZE_COMMAND];
		char* command_option[SIZE_COMMAND_PARSE]={NULL};
		char command_name[SIZE_NAME];
		int res=0; 
		res=input_command(command);
		if(res==0){
			output_error(); 
			continue;
		}
		if(res==-1)return ;
		parse_command(command,command_name,command_option);
		use_command(command_name,command_option);
	}
}
void use_command(char* command_name,char** command_option){
	pid_t pid =fork();
	if(pid==-1){
		perror("");
		exit(1);
	}
	if(pid==0){
		int res=execvp(command_name,command_option);
		if(res==-1){
			output_error();
			perror("");
			exit(1);
		}
	}else{
		pid_t cpid =0;
		int status=0;
		while((cpid=waitpid(-1,&status,WNOHANG))==0);
	}
}
int input_command(char* command){
	printf("=====>");
	fgets(command,SIZE_COMMAND,stdin);
	command[strlen(command)-1]='\0';
	if(strlen(command)==0)return 0;
    if(strcmp(command,"exit")==0)return -1;
	return 1;
}
void parse_command(char* command,char* command_name,char** command_option){
	char* tokenPtr=strtok(command," ");
	strcpy(command_name,tokenPtr);
	int count=0;
	while(tokenPtr!=NULL){
		command_option[count++]=tokenPtr;
		tokenPtr=strtok(NULL," ");
	}
	command_option[count]=NULL;
}
void output_error(){
	printf("输入错误，请重新输入！\n");
}
